package com.myserver.core;

import com.myserver.util.JsonConfigUtil;
import net.sf.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

public class ServletContext {
    //通过类名创建servlet对象
    private static Map<String, String> servlet ;
    //通过请求名找到对应的servlet类名
    private static Map<String , String> mapping ;
    private static String contextPath;
    private static String staticPath;
    public ServletContext() {

    }
    /*初始化，加载配置资源*/
    static {
        servlet = new HashMap<>();
        mapping = new HashMap<>();
        contextPath = System.getProperty("user.dir");
        //解析json文件获得映射信息
        JSONObject webConfig = JsonConfigUtil.getJsonObject(contextPath+"\\src\\main\\resources\\web.json");
        //解析url映射
        JSONObject mappingJson = (JSONObject) webConfig.get("mapping");
        for (Object key : mappingJson.keySet()) {
            mapping.put((String) key, (String) mappingJson.get(key));
        }
        //解析servlet映射
        JSONObject servletJson = (JSONObject) webConfig.get("servlet");
        for (Object key : servletJson.keySet()) {
            servlet.put((String) key, (String) servletJson.get(key));
        }
        //解析html映射
        staticPath =  (String) webConfig.get("static");
    }
    public static Servlet getServlet(String action) {
        if ("".equals(action) || action == null) {
            return null;
        }
        String servlet_name = mapping.get(action);
        if(servlet_name==null){
            return null;
        }
        Servlet ser = null;
        try {
            ser = (Servlet) Class.forName(servlet.get(servlet_name)).newInstance();
        } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
            e.printStackTrace();
            return null;
        }
        return ser;
    }

    public static Map<String, String> getServlet() {
        return servlet;
    }

    public static void setServlet(Map<String, String> servlet) {
        ServletContext.servlet = servlet;
    }

    public static Map<String, String> getMapping() {
        return mapping;
    }

    public static void setMapping(Map<String, String> mapping) {
        ServletContext.mapping = mapping;
    }

    public static String getContextPath() {
        return contextPath;
    }

    public static void setContextPath(String contextPath) {
        ServletContext.contextPath = contextPath;
    }

    public static String getStaticPath() {
        return staticPath;
    }

    public static void setStaticPath(String staticPath) {
        ServletContext.staticPath = staticPath;
    }
}
